﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LuaInterface;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;

public class AddressableLuaScriptLoader : LuaFileUtils
{
    public bool LoadDone = false;
    public float PercentComplete = 1f;

    private const string PREFIX = "Assets/AddressableAssets/";
    private const string LUA_POSTFIX = ".lua";
    private const string LUA_LABEL = "lua";

    private static readonly Dictionary<string, AsyncOperationHandle<TextAsset>> luaMap = new Dictionary<string, AsyncOperationHandle<TextAsset>>();
    private static string[] files;

    public static string[] LuaFiles()
    {
        if (files == null)
        {
            var keys = new List<string>(luaMap.Keys);
            files = new string[keys.Count];
            for(int i = 0; i < keys.Count; i++)
            {
                files[i] = keys[i];
            }
        }
            
        return files;
    }

    public AddressableLuaScriptLoader(){
        instance = this;
        beZip = false;
    }

    public override byte[] ReadFile(string fileName)
    {
        if (!fileName.EndsWith(LUA_POSTFIX))
            fileName += LUA_POSTFIX;

        if(luaMap.TryGetValue(fileName, out var handle)) {
            return handle.Result.bytes;
        }
        else
        {
            throw new KeyNotFoundException($"Lua file named {fileName} can not be found.Check the name on addressable file list.Try reimport luascript floder to add missing file.");
        }
    }

    public IEnumerator LoadLuaScripts()
    {
        var handle = Addressables.LoadResourceLocationsAsync(LUA_LABEL, typeof(TextAsset));
        yield return handle;

        PercentComplete = 0f;

        foreach (var location in handle.Result)
        {
            Addressables.LoadAssetAsync<TextAsset>(location).Completed += (textHandle) =>
            {
                luaMap.Add(location.PrimaryKey, textHandle);
                PercentComplete = luaMap.Count / handle.Result.Count;
            };            
        }
        yield return new WaitUntil(()=> luaMap.Count == handle.Result.Count);
        Addressables.Release(handle);
    }
}
